package com.moco.launcher.fragment;

import android.annotation.SuppressLint;
import android.app.Activity;
import android.graphics.Bitmap;
import android.graphics.Bitmap.Config;
import android.graphics.BitmapFactory;
import android.net.Uri;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.view.LayoutInflater;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewGroup;
import android.widget.ImageView;
import android.widget.Toast;

import com.alibaba.fastjson.JSON;
import com.android.volley.AuthFailureError;
import com.android.volley.Request.Method;
import com.android.volley.Request;
import com.android.volley.RequestQueue;
import com.android.volley.Response;
import com.android.volley.VolleyError;
import com.android.volley.toolbox.ImageRequest;
import com.android.volley.toolbox.StringRequest;
import com.android.volley.toolbox.Volley;
import com.moco.launcher.R;
import com.moco.launcher.activity.MainActivity;
import com.moco.launcher.adapter.DataAdapter;
import com.moco.launcher.bean.MOCO_CONSTANTS;
import com.moco.launcher.bean.MusicCategoryDataBean;
import com.moco.launcher.bean.PickItemInfo;
import com.moco.launcher.dialog.WaitDialog;
import com.moco.launcher.listener.CloudListener;
import com.moco.launcher.listener.OnMusicCategorySelectedListener;
import com.moco.launcher.view.CategoryPickerView;
import com.nostra13.universalimageloader.core.DisplayImageOptions;
import com.nostra13.universalimageloader.core.ImageLoader;
import com.nostra13.universalimageloader.core.assist.FailReason;
import com.nostra13.universalimageloader.core.assist.ImageScaleType;
import com.nostra13.universalimageloader.core.listener.SimpleImageLoadingListener;
import com.oazon.common.Assert;
import com.oazon.common.Logger;
import com.oazon.common.TaskHelper;
import com.oazon.common.TaskHelper.Task;
import com.oazon.common.util.Blur;
import com.oazon.common.util.ImageUtils;
import com.oazon.common.util.RequestManager;
import com.oazon.common.util.StringUtils;
import com.oazon.common.util.Utils;
import com.oazon.moco.bean.McServiceMsg;
import com.oazon.moco.bean.Metadata;
import com.oazon.moco.lan.util.UrlDecode;
import com.oazon.moco.link.core.LinkSDK;
import com.oazon.moco.playlist.PlayListManage;
import com.oazon.moco.playlist.bean.AbstractMedia;
import com.oazon.moco.playlist.bean.GetMediaActionResponse;
import com.oazon.moco.playlist.bean.ItemType;
import com.oazon.moco.playlist.bean.MediaCollection;
import com.oazon.moco.playlist.bean.MediaCollectionBean;
import com.oazon.moco.playlist.bean.MediaMetadata;
import com.oazon.moco.playlist.bean.MediaMetadataBean;
import com.oazon.sonos.bean.GetMetadata;
import com.oazon.sonos.bean.GetMetadataResponse;
import com.oazon.sonos.core.SonosControler;
import com.oazon.sonos.listener.SonosListener;
import com.oazon.sonos.util.SonosUtil;

import io.netty.handler.codec.http.HttpMethod;

import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Map.Entry;
import java.util.Timer;
import java.util.TimerTask;

/**
 * 针对MusicCategoryFragment
 *
 * @author Gavin
 */
@SuppressLint("ValidFragment")
public class MusicCategoryFragment extends BaseFragment {

	private static final String ROOT = "root";
	private static final String PLAY_ALL = "播放全部";
	private static final String TAG = "MusicCateg";
	private List<PickItemInfo> data = new ArrayList<PickItemInfo>();
	private GetMetadataResponse<AbstractMedia> metadataResult = new GetMetadataResponse<AbstractMedia>();
	private List<AbstractMedia> abstractMedias = new ArrayList<AbstractMedia>();
	private List<MediaMetadata> mediaMetadatas = new ArrayList<MediaMetadata>();
	public CategoryPickerView mPickerView = null;
	private ImageView exitImageView = null;
	private OnMusicCategorySelectedListener mListener;
	private int nLevel = 0;
	private DisplayImageOptions options;
	private ImageView categoryBack = null;
	private ImageView category_selector = null;
	private boolean isFirstGetList = true;
	private String parentID = "";
	private ImageView rightIcon;
	private String provider = null;

	private Date updateDate = null;

	private Timer requestTimer;
	private Handler requesterHandler;
	private boolean requesttoastflag = true;
	private ImageView aboutview;

	private Map<String, Integer> saveChildIndex = new HashMap<String, Integer>();

	private McServiceMsg serviceMsg;
	private boolean addflag = true;
	// add an empty constructor to resolve umeng error
	public MusicCategoryFragment() {

	}

	public MusicCategoryFragment(McServiceMsg serviceMsg) {
		if (serviceMsg == null) {
			this.provider = "moco";
		} else {
			this.provider = serviceMsg.getProvider();
		}
		this.serviceMsg = serviceMsg;
		saveChildIndex.put(ROOT, 1);
	}

	@SuppressLint("UseSparseArrays")
	private Map<Integer, String> roots = new HashMap<Integer, String>();

	private boolean isRequestEnd = true;

	public String getProvider() {
		return provider;
	}

	public McServiceMsg getServiceMsg() {
		return serviceMsg;
	}

	public String getParentID() {
		return parentID;
	}

	public Map<String, Integer> getSaveChildIndex() {
		return saveChildIndex;
	}

	public int getnLevel() {
		return nLevel;
	}

	public Map<Integer, String> getRoots() {
		return roots;
	}

	public void setServiceMsg(MusicCategoryDataBean bean) {
		if (bean == null) {
			return;
		}
		this.serviceMsg = bean.getServiceMsg();
		this.saveChildIndex = bean.getSaveChildIndex();
		this.nLevel = bean.getnLevel();
		this.roots = bean.getRoots();
		this.parentID = bean.getParentID();
		if (serviceMsg == null) {
			this.provider = "moco";
		} else {
			this.provider = serviceMsg.getProvider();
		}
		requestProviderIcon();
		if (StringUtils.isBlank(parentID)) {
			parentID = ROOT;
		}
		getQueueList(parentID, provider);
		reflashExitview();
	}

	@Override
	public void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		ImageScaleType imageScaleType = ImageScaleType.EXACTLY_STRETCHED;
		options = new DisplayImageOptions.Builder()
				.showImageForEmptyUri(R.drawable.category_line)
				.showImageOnLoading(R.drawable.category_line)
				.cacheInMemory(true).cacheOnDisc(true)
				.imageScaleType(imageScaleType).considerExifParams(true)
				.bitmapConfig(Bitmap.Config.RGB_565).build();
	}

	@Override
	public void onAttach(Activity activity) {
		super.onAttach(activity);
		mListener = (OnMusicCategorySelectedListener) activity;
	}

	WaitDialog dialog;

	private void getQueueList(final String parentId, final String provider) {
		Logger.i(TAG, "isFirstGetList==" + isFirstGetList);
		if (preGetList(parentId, provider))
			return;

		final GetMetadata parameters = SonosUtil.fillgetMetadata(parentId,
				MOCO_CONSTANTS.INDEX, MOCO_CONSTANTS.QUEUE_COUNT,
				MOCO_CONSTANTS.RECURSIVE, provider);

		SonosControler.getInstance(this.getContext(), serviceMsg).getMetadata(
				this.getContext(), parameters, new SonosListener() {

					@Override
					public void onResponse(Object response) {
						isCategoryNull(response);
						if (response instanceof GetMetadataResponse) {
							if (dialog != null && dialog.isShowing()) {
								dialog.dismiss();
							}
							requestTimer.cancel();
							isRequestEnd = true;
							try {
								metadataResult = (GetMetadataResponse) response;
								if (metadataResult == null)
									return;
								List<AbstractMedia> abstractMediasResult = metadataResult
										.getGetMetadataResult()
										.getMediaCollectionOrMediaMetadata();
								if (abstractMediasResult.size() > 0) {
									abstractMedias.clear();
									mediaMetadatas.clear();
									final List<MediaCollectionBean> mediaCollectionBeans = new ArrayList<MediaCollectionBean>();
									final List<MediaMetadataBean> mediaMetadataBeans = new ArrayList<MediaMetadataBean>();

									for (AbstractMedia am : abstractMediasResult) {
										if (am == null)
											continue;
										abstractMedias.add(am);
										if (am instanceof MediaCollection) {

											mediaCollectionBeans.add(DataAdapter
													.parseMediaCollection(
															(MediaCollection) am,
															parentId, provider));
										} else if (am instanceof MediaMetadata) {
											mediaMetadataBeans.add(DataAdapter
													.paseMediaMetadata(
															(MediaMetadata) am,
															parentId, provider));
											mediaMetadatas
													.add((MediaMetadata) am);
										}
									}// end for

									TaskHelper.exec(new Task() {
										@Override
										public void execute() throws Exception {
											RequestManager
													.insertListMediaCollection(mediaCollectionBeans);
											RequestManager

													.insertListMediaMetadata(mediaMetadataBeans);
											/*
											 * if (mediaMetadatas != null &&
											 * mediaMetadatas.size() > 0) {
											 * 
											 * postO2Songlist(MOCO_CONSTANTS.
											 * POST_TO_O2_SONGSLIST,provider,
											 * JSON
											 * .toJSON(mediaMetadatas).toString
											 * ()); Logger.i(TAG,
											 * "postO2Songlist==" +
											 * JSON.toJSON(mediaMetadatas
											 * ).toString()); }
											 */

										}

										@Override
										public void callback(Exception e) {
											if (e != null)
												Logger.e(
														TAG,
														"save db callback: "
																+ e.getMessage());
											else
												Logger.d(TAG,
														"save db callback success");
										}
									});

									Logger.d(TAG, "notifyDataChanged1");
									notifyDataChanged();
									Logger.d(TAG, "notifyDataChanged2");
								}
							} catch (Exception e) {
								onError(0, e.getMessage());
							}

						}
					}

					@Override
					public void onError(int err, String msg) {
						getListError(msg);
					}
				});
	}

	private void isCategoryNull(Object response) {
		if (response == null) {
			if (dialog != null && dialog.isShowing()) {
				dialog.dismiss();
			}
			exitImageView.callOnClick();
			Toast.makeText(mContext, "还未添加内容!", Toast.LENGTH_SHORT).show();
			return;
		}
	}

	private void getRadioList(final String parentId, final String provider) {
		Logger.i(TAG, "isFirstGetList==" + isFirstGetList);
		if (preGetList(parentId, provider))
			return;

		final GetMetadata parameters = SonosUtil.fillgetMetadata(parentId,
				MOCO_CONSTANTS.INDEX, MOCO_CONSTANTS.RADIO_COUNT,
				MOCO_CONSTANTS.RECURSIVE, provider);

		SonosControler.getInstance(this.getContext(), serviceMsg).getMetadata(
				this.getContext(), parameters, new SonosListener() {

					@Override
					public void onResponse(Object response) {
						isCategoryNull(response);
						if (response instanceof GetMetadataResponse) {
							if (dialog != null && dialog.isShowing()) {
								dialog.dismiss();
							}
							requestTimer.cancel();
							isRequestEnd = true;
							try {
								metadataResult = (GetMetadataResponse) response;
								if (metadataResult == null)
									return;

								List<AbstractMedia> abstractMediasResult = metadataResult
										.getGetMetadataResult()
										.getMediaCollectionOrMediaMetadata();
								List<Metadata> metadatas = DataAdapter
										.paseMetadatas(
												abstractMediasResult,
												parentID,
												MusicCategoryFragment.this.provider);
								PlayListManage.getInstance().toSmartRadio(
										parameters);
								mListener.onMusicListSelected(metadatas);
							} catch (Exception e) {
								onError(0, e.getMessage());
							}

						}
					}

					@Override
					public void onError(int err, String msg) {
						getListError(msg);
					}
				});
	}

	private void getListError(String msg) {
		if (dialog != null && dialog.isShowing()) {
			dialog.dismiss();
		}
		Logger.d(TAG, "err= " + msg);
		isRequestEnd = true;
		requestTimer.cancel();

		MainActivity aa = (MainActivity) getContext();
		if (Utils.isWifiConnected(aa)) {
			Toast.makeText(getContext(), "请检查网络", Toast.LENGTH_SHORT).show();
		} else {/*
				 * Intent intent = new Intent(getContext(),
				 * NewWifiSettingsActivity.class); startActivity(intent);
				 */
		}
	}

	private boolean preGetList(final String parentId, final String provider) {
		if (!isFirstGetList) {
			dialog = WaitDialog.createDialog(getContext());
			dialog.show();
			// if (!Utils.hasNetwork(getContext())) {
			if (!Utils.isWifiConnectedOrConnecting(getContext())) {
				Toast.makeText(getContext(), "WiFi未连接", Toast.LENGTH_SHORT)
						.show();
				if (dialog != null && dialog.isShowing()) {
					dialog.dismiss();
				}
				return true;
			}

		}
		isFirstGetList = false;
		isRequestEnd = false;
		if (checkExpire()) {
			Logger.d(TAG, "getList data expire, delete data by parentId:"
					+ parentId + " provider:" + provider);
			RequestManager.deleteByParentId(parentId, provider);
		} else {
			if (readCache(parentId, provider)) {
				return true;
			}
		}

		// 2015.06.08--#219--Taylor
		if (requestTimer != null) {
			requestTimer.cancel();
		}
		requestTimer = new Timer();
		TimerTask timerTask = new TimerTask() {
			@Override
			public void run() {
				if (requesttoastflag == true) {
					if (requesterHandler != null) {
						requesterHandler.sendEmptyMessage(0x123);
						Logger.i(TAG, "取消Toast显示"
								+ MusicCategoryFragment.this.provider);
					}
				}
			}
		};
		requestTimer.schedule(timerTask, 10000, 15000);
		return false;
	}

	private boolean readCache(final String parentId, final String provider) {
		List<MediaCollectionBean> mediaCollectionBeans;
		List<MediaMetadataBean> mediaMetadataBeans;
		mediaCollectionBeans = RequestManager.requsetMediaCollectionBean(
				parentId, provider);
		if (mediaCollectionBeans.size() > 0) {
			abstractMedias.clear();
			for (MediaCollectionBean mediaCollectionBean : mediaCollectionBeans) {
				MediaCollection collection = DataAdapter
						.paseMediaCollectionBean(mediaCollectionBean);
				if (collection != null) {
					abstractMedias.add(collection);
				}
			}
			if (dialog != null && dialog.isShowing()) {
				dialog.dismiss();
			}
			isRequestEnd = true;
			notifyDataChanged();
			return true;
		}

		mediaMetadataBeans = RequestManager.requsetMediaMetadataBean(parentId,
				provider);
		if (mediaMetadataBeans.size() > 0) {
			abstractMedias.clear();
			for (MediaMetadataBean mediaMetadataBean : mediaMetadataBeans) {
				MediaMetadata mm = DataAdapter
						.paseMediaMetadataBean(mediaMetadataBean);
				if (mm != null) {
					abstractMedias.add(mm);
				}
			}
			if (dialog != null && dialog.isShowing()) {
				dialog.dismiss();
			}
			isRequestEnd = true;
			notifyDataChanged();
			return true;
		}
		return false;
	}

	public void refreshRootPage(boolean toRepalce) {
		isRequestEnd = true;
		if (checkExpire() || toRepalce) {
			try {
				RequestManager.deleteByParentId(ROOT, provider);
				getQueueList(ROOT, provider);
				updateDate = new Date();
				Logger.d(TAG, "refreshRootPage");
			} catch (Exception e) {
				updateDate = null;
				Logger.e(TAG, "refreshRootPage error: " + e.getMessage());
			}
		}

	}

	private boolean checkExpire() {
		if (updateDate != null) {
			Long updateLong = updateDate.getTime();
			Long now = new Date().getTime();
			if (now - updateLong < 3600 * 1000) {
				return false;
			} else {
				return true;
			}
		}

		return true;
	}

	private void notifyDataChanged() {
		data.clear();
		for (int i = 0; i < abstractMedias.size(); i++) {
			PickItemInfo item = new PickItemInfo();
			item.setText(abstractMedias.get(i).getTitle());
			item.setId(abstractMedias.get(i).getId());
			data.add(item);
		}

		//if (abstractMedias.get(0).getItemType() == ItemType.TRACK) {
		if (abstractMedias.get(0).getItemType() == ItemType.TRACK && !abstractMedias.get(1).getId().equals(PLAY_ALL)) {

			PickItemInfo item = new PickItemInfo();
			item.setText(PLAY_ALL);
			item.setId(PLAY_ALL);
			AbstractMedia mc = new MediaMetadata();
			mc.setTitle(PLAY_ALL);
			mc.setId(PLAY_ALL);
			// mc.setItemType(ItemType.TRACK);
			abstractMedias.add(1, mc);
			data.add(1, item);
		}

		if (abstractMedias.get(0).getItemType() == ItemType.PROGRAM
				|| abstractMedias.get(0).getItemType() == ItemType.TRACK) {
			rightIcon.setVisibility(View.INVISIBLE);
		} else {
			rightIcon.setVisibility(View.VISIBLE);
		}

		if (roots.get(nLevel) == null
				|| saveChildIndex.get(roots.get(nLevel)) == null) {
			mPickerView.setSelected(1);
		} else {
			// mPickerView.setSelected(saveChildIndex.get(roots.get(nLevel)));
			reSortList(data, saveChildIndex.get(roots.get(nLevel)));
		}
		fixOneItemView();
		mPickerView.setData(data);

		mPickerView.post(new Runnable() {

			@Override
			public void run() {
				mPickerView.invalidate();
			}
		});

		// TODO gavin displayItemInfo(mPickerView.getCurrentSelectId());
	}

	private void fixOneItemView() {
		if (data == null || data.size() == 0) {
			return;
		}
		if (data.size() == 1) {
			PickItemInfo info = new PickItemInfo();
			info.setText("");
			info.setId("");
			data.add(0, info);

			info = new PickItemInfo();
			info.setText("");
			info.setId("");
			data.add(info);

			AbstractMedia mc = new MediaMetadata();
			mc.setTitle("");
			info.setId("");
			abstractMedias.add(0, mc);

			mc = new MediaMetadata();
			mc.setTitle("");
			info.setId("");
			abstractMedias.add(mc);
		}
	}

	public void postO2Songlist(String url, String provider, String str) {
		if (provider == "o2") {
			return;
		}
		url = url.replace(" ", "");
		// 向服务器post 从网易加载的歌单 ，并且在返回函数中添加喜欢属性 对用户以前删除歌曲进行处理
		final Map<String, String> param = new HashMap<String, String>();

		param.put("provider", provider);
		param.put("mediaMetadatas", str);
		RequestQueue queue = RequestManager.getRequestQueue();
		Logger.d(TAG, "Responseurl==" + url);

		StringRequest request = new StringRequest(Method.POST, url,
				new Response.Listener<String>() {

					@Override
					public void onResponse(String response) {
						Logger.d(TAG, "postO2Songlist_onResponse==" + response);
						Assert.notNull(response);
						try {

							GetMediaActionResponse mediaresponse = new GetMediaActionResponse();
							mediaresponse = JSON.parseObject(response,
									GetMediaActionResponse.class);
							Map<String, String> actions = new HashMap<String, String>();
							actions = mediaresponse.getActions();
							if (actions == null) {
								return;
							}
							for (Entry<String, String> entry : actions
									.entrySet()) {
								if (entry.getValue().equals("favorite")) {
									Metadata metadata = PlayListManage
											.getInstance().getIndexMetadata(
													entry.getKey());
									if (metadata != null) {
										PlayListManage
												.getInstance()
												.getIndexMetadata(
														entry.getKey())
												.setFavorite(true);
									}
								} else if (entry.getValue().equals("removed")) {
									for (AbstractMedia am : abstractMedias) {
										if (am == null)
											continue;
										if (am.getId() == entry.getKey()) {
											abstractMedias.remove(am);
										}
									}
									int i = PlayListManage.getInstance()
											.getIndex(entry.getKey());
									if (i != -1) {
										PlayListManage.getInstance().remove(i);
									}
								} else {

								}
							}
						} catch (Exception e) {
							Logger.e(TAG, "清除列表崩溃:" + e.getMessage());
						}

					}
				}, new Response.ErrorListener() {

					@Override
					public void onErrorResponse(VolleyError arg0) {
						Logger.e(
								TAG,
								"post_o2_songliston_ErrorResponse"
										+ arg0.getMessage());

					}
				}) {
			@Override
			protected Map<String, String> getParams() throws AuthFailureError {
				return param;
			}

			@Override
			public Map<String, String> getHeaders() throws AuthFailureError {
				Map<String, String> headers = new HashMap<String, String>();
				headers.put("deviceId", LinkSDK.UUID);
				return headers;
			}
		};

		queue.add(request);

	}

	// 向服务器请求当前歌曲是否细化或者删除
	public void requestIsLoveAndDeleateToO2(String url, String metadataid,
			String provider) {
		String urlrequesto2 = "http://";

		Map<String, String> params = new HashMap<String, String>();

		UrlDecode.parseParameters(params,
				MOCO_CONSTANTS.REGUES_LOVE_DELETE_URI, null);
		// loop list
		params.put("songId", metadataid);
		// end loop
		params.put("provider", provider);
		urlrequesto2 = UrlDecode.getUrl(params,
				MOCO_CONSTANTS.REGUES_LOVE_DELETE_URI, null);
		urlrequesto2 = urlrequesto2.replace(" ", "");
		Logger.i(TAG, "urlrequesto2==" + urlrequesto2);
		RequestManager.sendpost(getContext(), urlrequesto2,
				new CloudListener() {
					@Override
					public void onResponse(String response) {
						Logger.i(TAG, "IsLoveAndDeleate_To_o2_response=="
								+ response);
						if (response == null) {
							onError(0, "null");
							return;
						}
						GetMediaActionResponse mediaresponse = new GetMediaActionResponse();
						mediaresponse = JSON.parseObject(response,
								GetMediaActionResponse.class);
						Map<String, String> actions = new HashMap<String, String>();
						actions = mediaresponse.getActions();
						for (Entry<String, String> entry : actions.entrySet()) {
							entry.getKey();// song id

							if (entry.getValue() == "favorite") {
								PlayListManage.getInstance().getCurrentMedia()
										.setFavorite(true);
							} else if (entry.getValue() == "removed") {

							} else {

							}
						}

					}

					@Override
					public void onError(int err, String msg) {
						Logger.i(TAG, "IsLoveAndDeleate_To_o2_error==" + msg);
					}
				});

	}

	private synchronized void reSortList(List<PickItemInfo> data, int index) {
		if (index == 1 || index < 0 || data == null || data.size() <= 0) {
			return;
		}
		if (index - 1 < 0) {
			index = data.size() - 1;
		} else {
			index = index - 1;
		}

		for (int i = 0; i < index; i++) {
			PickItemInfo info = data.get(0);
			data.remove(0);
			data.add(info);
		}
	}

	@Override
	public View onCreateView(LayoutInflater inflater, ViewGroup container,
			Bundle savedInstanceState) {
		View rootView = null;
		/*
		 * if (provider.equals(MOCO_CONSTANTS.PROVIDER_DOUBAN)) { rootView =
		 * inflater.inflate(R.layout.category_layout_douban, container, false);
		 * } else if (provider.equals(MOCO_CONSTANTS.PROVIDER_WANNGYI)) {
		 * rootView = inflater.inflate(R.layout.category_layout_wangyi,
		 * container, false); } else { rootView =
		 * inflater.inflate(R.layout.category_layout, container, false); }
		 */
		rootView = inflater.inflate(R.layout.category_layout, container, false);
		categoryBack = (ImageView) rootView.findViewById(R.id.category_back);
		categoryBack.setDrawingCacheEnabled(true);
		setBackground();
		category_selector = (ImageView) rootView
				.findViewById(R.id.category_selector);
		mPickerView = (CategoryPickerView) rootView
				.findViewById(R.id.music_category_choice);

		rightIcon = (ImageView) rootView.findViewById(R.id.rightIcon);
		aboutview = (ImageView) rootView.findViewById(R.id.viewAbout);

		requestProviderIcon();
		mPickerView
				.setOnSelectListener(new com.moco.launcher.view.CategoryPickerView.onSelectListener() {
					@Override
					public boolean onRelayout(
							String selectId,
							com.moco.launcher.view.CategoryPickerView.UiParam param) {
						reflashExitview();

						return true;
					}

					@Override
					public boolean onStop(String nSelectId) {
						// TODO gavin displayItemInfo(nSelectId);
						Logger.i(TAG, "onStop === " + nSelectId);
						setBackground();
						if (roots.get(nLevel) == null) {
							return true;
						}
						int index = getCurSelectedIndex(nSelectId);
						
						saveChildIndex.put(roots.get(nLevel), index);
						Logger.i(TAG, "abstractMedias.get(index).getItemType()=="+abstractMedias.get(abstractMedias.size()-1).getItemType());
				//-----------------------------------------------
		        
						Logger.i(TAG, "Math.abs(abstractMedias.size()-index)>>>"+Math.abs(abstractMedias.size()-index)+">>>addflag=="+addflag);
							if(Math.abs(abstractMedias.size()-index)==3 && addflag==true){
								addSongsAtCurrentSongsList(roots.get(nLevel),provider,  abstractMedias.size());
								addflag = false;
							}
				//-----------------------------------------------
						Logger.d(
								TAG,
								"nLevel == " + nLevel + "root=="
										+ roots.get(nLevel) + "id==" + index);
						return true;
					}

					@Override
					public boolean onSelect(String nSelectId) {
						return true;
					}
				});
		// #feature fix 426
		mPickerView.setOnClickListener(new OnClickListener() {

			@Override
			public void onClick(View v) {
				if (CategoryPickerView.isUp == true)
					return;

				if (mPickerView.clickY < mPickerView.getHeight() / 3) {
					pickViewClick(v, -1);
				} else if (mPickerView.clickY > (mPickerView.getHeight() / 3) * 2) {
					pickViewClick(v, 1);
				} else if (mPickerView.clickY > mPickerView.getHeight() / 3
						|| mPickerView.clickY < (mPickerView.getHeight() / 3) * 2) {
					pickViewClick(v, 0);

				}
			}
		});

		exitImageView = (ImageView) rootView.findViewById(R.id.category_exit);
		exitImageView.setOnClickListener(new OnClickListener() {

			@Override
			public void onClick(View v) {
				if (nLevel <= 0)
					return;
				nLevel--;
				if (nLevel <= 0)
					nLevel = 0;
				getQueueList(roots.get(nLevel), provider);
			}
		});

		nLevel = 0;
		roots.put(0, "root");
		refreshRootPage(false);
		// 2015.06.08--#219--Taylor
		requesterHandler = new Handler() {
			@Override
			public void handleMessage(Message msg) {
				// TODO Auto-generated method stub
				super.handleMessage(msg);
				if (msg.what == 0x123) {
					Toast.makeText(getContext(), "网速较慢，请检查网络",
							Toast.LENGTH_SHORT).show();
				}
			}
		};

		return rootView;

	}

	private void reflashExitview() {
		if (exitImageView == null) {
			return;
		}
		if (nLevel > 0) {
			exitImageView.setVisibility(View.VISIBLE);
		} else {
			exitImageView.setVisibility(View.GONE);
		}
	}

	private void requestProviderIcon() {
		if (!Utils.isO2(provider)) {
			String providerLogoHttp = MOCO_CONSTANTS.PROVIDER_LOGO_URL
					+ provider + "_logo.png";

			RequestQueue queue = RequestManager.getRequestQueue();

			ImageRequest imagerequest = new ImageRequest(providerLogoHttp,
					new Response.Listener<Bitmap>() {

						@Override
						public void onResponse(Bitmap arg0) {
							if (aboutview == null) {
								return;
							}
							if (arg0 == null) {
								aboutview.setImageBitmap(BitmapFactory
										.decodeResource(getResources(),
												R.drawable.default_null_icon));
							} else {
								aboutview.setImageBitmap(arg0);
							}
						}
					}, 0, 0, Config.RGB_565, new Response.ErrorListener() {

						@Override
						public void onErrorResponse(VolleyError arg0) {
							aboutview.setImageBitmap(BitmapFactory
									.decodeResource(getResources(),
											R.drawable.default_null_icon));
						}
					});
			queue.add(imagerequest);
		}
	}

	private void setBackground() {
		if (categoryBack != null) {
			categoryBack.setImageResource(ids.get((int) (Math.random() * 4)));
		}
	}

	/*
	 * 通过mHandler 替换点击事件触发的图片，调换成原来图片
	 */
	Handler mHandler = new Handler() {

		@Override
		public void handleMessage(Message msg) {
			if (msg.what == 0x11) {
				category_selector.setImageResource(R.drawable.category_line);
			}
		}

	};

	@SuppressWarnings("null")
	public AbstractMedia getItemInfo(String id) {
		if (abstractMedias == null || id == null) {
			return null;
		}

		for (AbstractMedia mediaCollection : abstractMedias) {
			if (mediaCollection != null) {
				Logger.d(TAG, "" + mediaCollection.getId());

			}
			if (mediaCollection != null && mediaCollection.getId() == id) {
				return mediaCollection;
			}
		}
		return null;
	}

	public MediaMetadata getMediaMetadata(String id) {
		if (abstractMedias == null || id == null) {
			return null;
		}

		for (AbstractMedia mediaCollection : abstractMedias) {
			if (mediaCollection.getId() == id) {
				return (MediaMetadata) mediaCollection;
			}
		}
		return null;
	}

	public List<MediaMetadata> getMediaMetadataList(List<AbstractMedia> arg) {
		List<MediaMetadata> result = new ArrayList<MediaMetadata>();
		for (AbstractMedia am : abstractMedias) {
			if (!am.getTitle().equals(PLAY_ALL))
				result.add((MediaMetadata) am);
		}
		return result;
	}

	public boolean displayItemInfo(String nSelectId) {
		// MocoItemInfo info = getItemInfo(nSelectId);
		MediaCollection info = (MediaCollection) getItemInfo(nSelectId);
		if (info == null)
			return false;
		ImageLoader.getInstance().displayImage(info.getAlbumArtURI(),
				categoryBack, options, new SimpleImageLoadingListener() {
					@Override
					public void onLoadingStarted(String imageUri, View view) {

					}

					@Override
					public void onLoadingFailed(String imageUri, View view,
							FailReason failReason) {
						String message = null;
						switch (failReason.getType()) {
						case IO_ERROR:
							message = "Input/Output error";
							break;
						case DECODING_ERROR:
							message = "Image can't be decoded";
							break;
						case NETWORK_DENIED:
							message = "Downloads are denied";
							break;
						case OUT_OF_MEMORY:
							message = "Out Of Memory error";
							break;
						case UNKNOWN:
							message = "Unknown error";
							break;
						}
						Toast.makeText(MusicCategoryFragment.this.getContext(),
								message, Toast.LENGTH_SHORT).show();
					}

					@Override
					public void onLoadingComplete(String imageUri, View view,
							Bitmap loadedImage) {
						// ((ImageView)view).setImageBitmap(Blur.fastblur(getContext(),
						// ImageUtils.bitmap2Gray(loadedImage), 20));
						((ImageView) view).setImageBitmap(ImageUtils
								.bitmap2Gray(Blur.fastblur(getContext(),
										loadedImage, 20)));

					}
				});

		return true;
	}

	@Override
	public void setUserVisibleHint(boolean isVisibleToUser) {
		Logger.e(TAG, "seMusicCatetUserVisibleHint==" + isVisibleToUser);
		if (!isVisibleToUser) {
			if (mPickerView != null) {
				mPickerView.pauseMoveTxt();
			}
			if (dialog != null && dialog.isShowing()) {
				dialog.dismiss();
			}
			requesttoastflag = false;
		} else {
			if (mPickerView != null) {
				mPickerView.pauseMoveTxt();
				mPickerView.startUpdateView();
				mPickerView.setClickable(true);
			}
			requesttoastflag = true;
			reflashExitview();
		}
	}

	@Override
	public void onStop() {
		if (dialog != null && dialog.isShowing()) {
			dialog.dismiss();
		}
		requesttoastflag = false;

		super.onStop();
	}
	
	public void pickViewClick(View v, int indexDiff) {

		Logger.d(TAG, "ONCLICK.......");
		Logger.d(TAG, "CategoryPickerView.isUp==" + CategoryPickerView.isUp
				+ " isRequestEnd:" + isRequestEnd);

		if (!isRequestEnd) {
			dialog = WaitDialog.createDialog(getContext());
			dialog.show();
			return;
		}

		if (abstractMedias == null || abstractMedias.isEmpty()) {
			getQueueList(ROOT, provider);
		}

		CategoryPickerView view = (CategoryPickerView) v;
		AbstractMedia info = getItemInfo(view
				.getCurrentSelectId(view.mCurrentSelected + indexDiff));
/*		Logger.d(
				TAG,
				"info: "
						+ info
						+ " id:"
						+ view.getCurrentSelectId(view.mCurrentSelected
								+ indexDiff)
						+ " selectid:"
						+ view.getCurrentSelectId(view.mCurrentSelected
								+ indexDiff));*/
		if (view.getCurrentSelectId(view.mCurrentSelected + indexDiff).equals(
				PLAY_ALL)) {
			Assert.notNull(abstractMedias);
			Logger.i(TAG, "PLAY_ALL:" + abstractMedias.size());
			PlayListManage.getInstance().toQueue();
			mListener.onMusicListSelected(getMediaMetadataList(abstractMedias),
					false, parentID, provider);
			return;
		} else {
			Logger.e(
					TAG,
					"PLAY_ALL"
							+ view.getCurrentSelectId(view.mCurrentSelected
									+ indexDiff));
		}

		if (info != null) {
			if (info.getItemType() != ItemType.TRACK
					&& info.getItemType() != ItemType.PROGRAM) {
				parentID = info.getId();
				nLevel++;
				roots.put(nLevel, info.getId());
				getQueueList(info.getId(), provider);

			} else {
				if (info.getItemType() == ItemType.TRACK) {
					Logger.i(TAG, "ItemType.TRACK");
					PlayListManage.getInstance().toQueue();
					mListener.onMusicSelected(getMediaMetadata(view
							.getCurrentSelectId(view.mCurrentSelected
									+ indexDiff)), parentID, provider);

				} else if (info.getItemType() == ItemType.PROGRAM) {
					Logger.i(TAG, "ItemType.PROGRAM");
					getRadioList(info.getId(), provider);

				}
			}
		}
	}

	private synchronized int getCurSelectedIndex(String id) {
		int index = -1;
		if (abstractMedias == null && abstractMedias.size() <= 0 && id == null) {
			return index;
		}
		for (int i = 0; i < abstractMedias.size(); i++) {
			if (id.equals(abstractMedias.get(i).getId())) {
				index = i;
			}
		}
		return index;
	}

	@Override
	public void onPause() {
		Logger.d(TAG, "onPause==");
		mPickerView.pauseMoveTxt();
		super.onPause();
	}
	
	@Override
	public void onResume() {
		Logger.d(TAG, "onResume==");
		mPickerView.releceMoveTxtPause();
		super.onResume();
	}
	@Override
	public void onDestroy() {
		if (mPickerView != null) {
			mPickerView.stopMoveTxt();
		}
		super.onDestroy();
	}

	@Override
	public void onDestroyView() {
		super.onDestroyView();
	}

	@Override
	public void onDetach() {
		super.onDetach();
	}
	
	private void addSongsAtCurrentSongsList(final String parentId, final String provider,final int songscount){
		final int lastLevel = nLevel;
		final String lastLevelList = roots.get(roots.size()-1);
		final GetMetadata songsparameters = SonosUtil.fillgetMetadata(parentId,
				songscount, MOCO_CONSTANTS.PAGE_COUNT,
				MOCO_CONSTANTS.RECURSIVE, provider);
		GetMetadataResponse<AbstractMedia> songsmetadataResult = new GetMetadataResponse<AbstractMedia>();
		Logger.i(TAG, "addSongsAtCurrentSongsList\\parentId=="+parentId+"\\provider=="+provider);
		SonosControler.getInstance(this.getContext(), serviceMsg).getMetadata(this.getContext()	, songsparameters, new SonosListener() {
			
			@Override
			public void onResponse(Object response) {
				// TODO Auto-generated method stub
				
				if(lastLevel!=nLevel || !lastLevelList.equals(roots.get(roots.size()-1))){
					Logger.i(TAG, "当前页面已经跳转，故不加载");
					addflag = true;//2
					return;
				}
				if(response==null){
					Logger.i(TAG, "addSongsAtCurrentSongsList-response==NUll");
					addflag = true;//2
					return;
					
				}
				Logger.i(TAG, "addSongsAtCurrentSongsList-response=="+response.toString());
				isCategoryNull(response);
				if(response instanceof GetMetadataResponse) {
					GetMetadataResponse songsmetadataResult = (GetMetadataResponse) response;
					if (songsmetadataResult == null)
						return;
					List<AbstractMedia> abstractMediasResult = songsmetadataResult
							.getGetMetadataResult()
							.getMediaCollectionOrMediaMetadata();
					if(abstractMediasResult.size()>0){
						final List<MediaMetadataBean> addsongsmediaMetadataBeans = new ArrayList<MediaMetadataBean>();
						final List<MediaCollectionBean> mediaCollectionBeans = new ArrayList<MediaCollectionBean>();//2
						final List<AbstractMedia> absListtemp = new ArrayList<AbstractMedia>() ;//2
						absListtemp.addAll(abstractMediasResult);//2
					
						//先去除重复的标签
						//for 循环为暂时性。发现歌曲分类会返回多个同样内容的结果--taylor 7.6
						for(AbstractMedia am: absListtemp){//2
							for(AbstractMedia ab: abstractMedias){//2
								if(ab.getId().equals(am.getId())){//2
									abstractMediasResult.remove(am);//2
								}
							}
						}
						for(AbstractMedia am: abstractMediasResult){
							if(am == null){
								continue;
							}
							Logger.i(TAG, "addSongsAtCurrentSongsList===am=="+am.getTitle());
							abstractMedias.add(am);
							Logger.i(TAG, "添加歌曲之后adstractMedias"+abstractMedias.size());
							if (am instanceof MediaCollection) {//2

								mediaCollectionBeans.add(DataAdapter//2
										.parseMediaCollection(//2
												(MediaCollection) am,//2
												parentId, provider));//2
							}else if(am instanceof MediaMetadata){//2
								addsongsmediaMetadataBeans.add(DataAdapter
										.paseMediaMetadata(
												(MediaMetadata) am,
												parentId, provider));
							}
							
						}
						addflag = true;
						TaskHelper.exec(new Task() {
							
							@Override
							public void execute() throws Exception {
								// TODO Auto-generated method stub
								RequestManager//2
								.insertListMediaCollection(mediaCollectionBeans);//2
								RequestManager
								.insertListMediaMetadata(addsongsmediaMetadataBeans);
							}
							@Override
							public void callback(Exception e) {
								// TODO Auto-generated method stub
								Logger.i(TAG, "call back");
							}
						});
						notifyDataChanged();
					}
				}
			}
			
			@Override
			public void onError(int err, String msg) {
				// TODO Auto-generated method stub
				Logger.i(TAG, "addsongs error");
			}
		});
	}
}
